function formatTime(date) {
    var year = date.getFullYear()
    var month = date.getMonth() + 1
    var day = date.getDate()
    var hour = date.getHours()
    var minute = date.getMinutes()
    var second = date.getSeconds()
    return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

function formatNumber(n) {
    n = n.toString()
    return n[1] ? n : '0' + n
}
/*
*request
*/
function request(parameter) {
    //url必填项
    if (!parameter || parameter == {} || !parameter.url) {
        console.log('Data request can not be executed without URL.');
        return false;
    } else {
        var murl = parameter.url;
        var headerCookie = getCookies();
        //判断是否有独自cookie请求
        var selfCookie = parameter.selfCookie;
        selfCookie && (headerCookie += selfCookie);
        // console.log(headerCookie);
        // parameter.data = jsonSerialize(parameter.data);
        //统一处理uid
        let u_id = wx.getStorageSync('u_id');
        if (u_id) {
            if(parameter.data){
                parameter.data.u_id = u_id;
            }else{
                parameter.data = {
                    u_id:u_id
                }
            }
        }
        console.log('接口-入参--' + murl.replace(/https:\/\/wechat.ajiuge.xyz\/run0823\/index.php\/api\/index/,''));
        console.log(parameter.data||'无参数');
        wx.request({
            url: murl,
            data: parameter.data || {},
            header: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'Cookie': headerCookie
            },
            method: parameter.method || 'POST',
            success: function (res) {
                setCookies(res.data);
                console.log('接口-出参--' + murl.replace(/https:\/\/wechat.ajiuge.xyz\/run0823\/index.php\/api\/index/,''));
                console.log(res||'无返回数据');
                parameter.success && parameter.success(res.data);

            },
            fail: function (e) {
                parameter.fail && parameter.fail(e);
                console.log(e.errMsg);
                wx.showToast({
                    title: '网络信号较差',
                    icon: 'loading',
                    duration: 3000
                });
            },
            complete: function () {
                parameter.complete && parameter.complete();
            }
        });
    }
}

function jsonSerialize(json) {
    var str = '';
    for (var key in json) {
        str += key + '=' + encodeURIComponent(json[key]) + '&';
    }
    //统一处理uid
    let u_id = wx.getStorageSync('u_id');
    if (u_id) {
        str += ('u_id=' + u_id + '&')
    }

    return str.substring(0, str.length - 1);
}

/*
*dealData
*zhixing.W
*/
function getCookies() {
    var value = '';
    try {
        let u_id = wx.getStorageSync('u_id');
        if (u_id) {
            value = value + `u_id=${u_id};`
        }
    } catch (e) {
        console.log(e);
    }
    return value;
}

function setCookies(data) {
    try {
        if (data && data.u_id) {
            wx.setStorageSync('u_id', data.u_id);
        }
    } catch (e) {
        console.log(e);
    }
}

function setUserInfo(e){
    // console.log(e);
    if(e.detail.encryptedData && e.detail.iv && e.detail.errMsg == 'getUserInfo:ok'){
        wx.setStorageSync('wxuserinfo', e.detail.userInfo);
    }else {
        wx.removeStorageSync('wxuserinfo');
        console.log("用户拒绝授权")
    }
}
function getUserInfo(){
    return wx.getStorageSync('wxuserinfo') || {};
}

/***
 * 提交订单
 * @type
 */
function gotopay(self,orderData) {
    var app = getApp();
    var oAppId = app.globalData.appid || '';
    var code;
    wx.login({//调用登录获取code换取openId和sessionkey
        success: function (res) {
            code = res.code;
            if (code) {
                orderData.code = code;
                orderData.appId = oAppId;
                app.util.request({
                    url: app.globalRequestUrl + '/order',
                    data:orderData,
                    success: function (result) { //调起微信支付
                        wx.hideToast();
                        if(result && result.msg == 'success'){
                            var o_id = result.o_id;
                            if(result.o_id){
                                self.data.o_id = o_id;
                                getPayParms(o_id,function (data) {
                                    data.o_id = o_id;
                                    wxPay(data);
                                })
                            }else{
                                wx.showModal({
                                    title:'提示',
                                    content:'提交订单失败，请稍后重试！',
                                    showCancel:false
                                });
                            }
                        }else{
                            wx.showModal({
                                title:'提示',
                                content:'提交订单失败，请稍后重试！',
                                showCancel:false
                            });
                        }
                    },
                    fail: function(){
                        wx.hideToast();
                    },
                    complete: function(){
                        self && (typeof self.enabledClick == 'function' ) && self.enabledClick();

                    }
                });
                //调用用户信息
            } else {
                console.log('获取用户登录态失败！' + res.errMsg)
            }
        }
    });
}

function getPayParms(o_id,callback) {
    var app = getApp()
    app.util.request({
        url: 'https://wechat.ajiuge.xyz/run0823/WxpayAPI/pay.php ',
        data:{
            o_id:o_id
        },
        success: function (result) { //调起微信支付
            wx.hideToast();
            if(result && result.appId && result.nonceStr){
                callback(result);
            }else{
                wx.showModal({
                    title:'提示',
                    content:'提交订单失败，请稍后重试！',
                    showCancel:false
                });
            }
        },
        fail: function(){
            wx.hideToast();
        },
        complete: function(){
            wx.hideToast();
            self && (typeof self.enabledClick == 'function' ) && self.enabledClick();

        }
    });
}
/***
 * 支付
 * @param parameter
 */
function wxPay(parameter) {
    //url必填项
    if (!parameter || parameter == {}) {
        console.log('Pay request can not be executed without param.');
        return false;
    }
    wx.requestPayment({
        'timeStamp': parameter.timeStamp,
        'nonceStr': parameter.nonceStr,
        'package': parameter.package,
        'signType': parameter.signType,
        'paySign': parameter.paySign,

        'success': function (payRes) {
            if (payRes.errMsg == 'requestPayment:ok') {
                wx.showToast({
                    title: '支付成功',
                    icon: 'success',
                });
                //支付失败，直接取消订单
                successOrder({o_id:parameter.o_id});
                setTimeout(function () {
                    wx.redirectTo({
                        url: '/pages/order/order'
                    });
                },1000)
            }
        },
        'fail': function (payRes) {
            //支付失败，直接取消订单
            cancelOrder({o_id:parameter.o_id});
            wx.showModal({
                title: '支付失败',
                confirmText: '我知道了',
                showCancel: false
            });
        },
        'complete': function (payRes) {
            //兼容旧版本支付
            if (payRes.errMsg == 'requestPayment:cancel') {
                cancelOrder({o_id:parameter.o_id});
            }
        }
    });//调起微信支付
}
//普通用户取消订单
function cancelOrder(orderData,callback){
    var data = {
        o_id:orderData.o_id
    }
    var app = getApp();
    app.util.request({
        url: app.globalRequestUrl + '/setorderdel',
        method:'GET',
        data:data,
        success: function (res) { //调起微信支付
            if(res && res.msg == 'success'){
                typeof callback == "function" && callback()
            }
        },
        fail: function(){
        },
        complete: function(){
            wx.hideToast();
        }
    });
}
//setorderget?uid=6&oid=27
//普通用户取消订单
function successOrder(orderData){
    var data = {
        o_id:orderData.o_id
    }
    var app = getApp();
    app.util.request({
        url: app.globalRequestUrl + '/setorderget',
        method:'GET',
        data:data,
        success: function (res) {},
    });
}
module.exports = {
    formatTime,
    request,
    getUserInfo,
    setUserInfo,
    setCookies,
    gotopay,
    cancelOrder
}
